import java.util.ArrayList;   
import java.util.List;
   
// 组件接口，所有具体组件和装饰器都要实现   
interface Component {
    void operation();   
}
   
// 具体组件类，实现组件接口   
class ConcreteComponent implements Component {
    @Override
    public void operation() {
        System.out.println("ConcreteComponent operation.");
    }   
}
   
// 装饰器抽象类，包含组件引用并实现组件接口   
abstract class Decorator implements Component {
    protected Component component;

    public Decorator(Component component) {
        this.component = component;
    }

    @Override
    public void operation() {
        if (component!= null) {
            component.operation();
        }
    }   
}
   
// 具体装饰器A类，添加额外行为   
class ConcreteDecoratorA extends Decorator {
    public ConcreteDecoratorA(Component component) {
        super(component);
    }

    @Override
    public void operation() {
        super.operation();
        this.addedBehavior();
    }

    private void addedBehavior() {
        System.out.println("ConcreteDecoratorA added behavior.");
    }   
}
   
// 具体装饰器B类，添加额外行为   
class ConcreteDecoratorB extends Decorator {
    public ConcreteDecoratorB(Component component) {
        super(component);
    }

    @Override
    public void operation() {
        this.addedBehavior();
        super.operation();
    }

    private void addedBehavior() {
        System.out.println("ConcreteDecoratorB added behavior.");
    }   
}
   
// 测试装饰者模式   
public class DecoratorPatternDemo {
    public static void main(String[] args) {
        // 先创建具体组件
        Component component = new ConcreteComponent();

        // 用装饰器A装饰组件
        Component decoratorA = new ConcreteDecoratorA(component);
        // 再用装饰器B装饰经过装饰器A装饰后的组件
        Component decoratorB = new ConcreteDecoratorB(decoratorA);

        // 执行最终装饰后的操作
        decoratorB.operation();
    }   
}


